package org.example.system.controller;

import org.example.system.common.base.BasePageQuery;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.example.system.common.result.Result;
import org.example.system.model.entity.BizLocation;
import org.example.system.model.dto.BizLocationDto;
import org.example.system.model.form.BizLocationForm;
import org.example.system.model.query.LocationPageQuery;
import org.example.system.model.vo.PageVo;
import org.example.system.service.BizLocationService;
import org.modelmapper.ModelMapper;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Tag(name = "14.网点管理")
@RestController
@RequestMapping("/api/v1/location")
@RequiredArgsConstructor
@Slf4j
public class BizLocationController {

    @Resource
    private BizLocationService bizLocationService;

    @Resource
    private ModelMapper modelMapper;

    @Operation(summary = "新增网点")
    @PostMapping("/add")
    public Result add(@RequestBody BizLocationForm bizLocationForm) {
        BizLocation location = modelMapper.map(bizLocationForm, BizLocation.class);
        bizLocationService.save(location);
        return Result.success();
    }

    @Operation(summary="删除网点")
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id) {
        BizLocation bizLocation = bizLocationService.getById(id);
        if (bizLocation == null) {
            return Result.failed("指定的网点不存在");
        }
        bizLocationService.removeById(id);
        return Result.success("删除网点成功");
    }

    @Operation(summary="修改网点信息")
    @PutMapping("/update")
    public Result update(@RequestBody BizLocationForm bizLocationForm){
        if(bizLocationForm.getId()==null){
            return Result.failed("网点id不能为空");
        }
        BizLocation bizLocationPo = modelMapper.map(bizLocationForm,BizLocation.class);
        bizLocationService.updateById(bizLocationPo);
        return Result.success("修改网点信息成功");
    }

    @Operation(summary = "网点分页查询")
    @PostMapping("/list")
    public Result queryLocationByPage(@RequestBody LocationPageQuery locationPageQuery)  {
        LambdaQueryWrapper<BizLocation> criteria = new LambdaQueryWrapper<>();
        if(StringUtils.hasLength(locationPageQuery.getKeywords())){
            criteria.and(wrap->wrap.like(BizLocation::getId,locationPageQuery.getKeywords())
                    .or().like(BizLocation::getTitle,locationPageQuery.getKeywords())
                    .or().like(BizLocation::getAddress,locationPageQuery.getKeywords())
                    .or().like(BizLocation::getPhone,locationPageQuery.getKeywords())
                    .or().like(BizLocation::getOpenTime,locationPageQuery.getKeywords())
                    .or().like(BizLocation::getLongitude,locationPageQuery.getKeywords())
                    .or().like(BizLocation::getLatitude,locationPageQuery.getKeywords()));
        }
        criteria.orderByDesc(BizLocation::getCreateTime);//按创建时间倒序排序
        if(locationPageQuery.getPageSize()>20){
            locationPageQuery.setPageSize(20);
        }
        int pageNum = locationPageQuery.getPageNum();
        int pageSize = locationPageQuery.getPageSize();
        Page<BizLocation> page = new Page<>(pageNum, pageSize);
        Page<BizLocation> bizLocationPage = bizLocationService.page(page, criteria);
        PageVo pageVo = new PageVo();
        pageVo.setTotal(bizLocationPage.getTotal());
        pageVo.setList(bizLocationPage.getRecords());
        return Result.success(pageVo);
    }
    @Operation(summary = "根据名称模糊分页查询")
    @PostMapping("/title") // 更改映射路径以反映新的查询类型
    public Result queryLocationByTitle(@RequestParam(value = "title", defaultValue = "") String title,
                                       @RequestBody BasePageQuery basePageQuery) {
        LambdaQueryWrapper<BizLocation> queryWrapper = new LambdaQueryWrapper<>();
        if (!title.isEmpty()) {
            queryWrapper.like(BizLocation::getTitle, title);
        }
        queryWrapper.orderByDesc(BizLocation::getCreateTime); // 保持按创建时间降序排列
        int pageNum = basePageQuery.getPageNum();
        int pageSize = basePageQuery.getPageSize();
        Page<BizLocation> page = new Page<>(pageNum, pageSize);
        bizLocationService.page(page, queryWrapper); // 执行分页查询
        PageVo pageVo = new PageVo();
        pageVo.setList(page.getRecords()); // 设置查询结果列表
        pageVo.setTotal(page.getTotal()); // 设置总记录数
        return Result.success(pageVo); // 返回查询结果
    }

    @Operation(summary = "根据当前时间分查询处于营业时间内的网点")
    @PostMapping("/now") // 更改映射路径以反映新的查询类型
    public Result queryLocationByNow(@RequestBody BasePageQuery basePageQuery) {
        // 定义时间格式
        DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm");
        LocalTime startTime = LocalTime.of(9,00);
        LocalTime endTime = LocalTime.of(21, 00);
        // 获取当前时间
        LocalTime now = LocalTime.now();
        // 构建查询条件
        LambdaQueryWrapper<BizLocation> queryWrapper = new LambdaQueryWrapper<>();
        if(now.isBefore(startTime) || now.isAfter(endTime)){
            queryWrapper.eq(BizLocation::getOpenTime,"00:00-24:00" );
        }
        queryWrapper.orderByDesc(BizLocation::getCreateTime); // 保持按创建时间降序排列
        int pageNum = basePageQuery.getPageNum();
        int pageSize = basePageQuery.getPageSize();
        Page<BizLocation> page = new Page<>(pageNum, pageSize);
        bizLocationService.page(page, queryWrapper); // 执行分页查询
        PageVo pageVo = new PageVo();
        pageVo.setList(page.getRecords()); // 设置查询结果列表
        pageVo.setTotal(page.getTotal()); // 设置总记录数
        return Result.success(pageVo); // 返回查询结果
    }

    @Operation(summary = "多条件分页查询网点")
    @PostMapping("/findBy")
    public Result findBy(@RequestBody BizLocationDto bizLocationDto,
                         @RequestBody BasePageQuery basePageQuery) {

        LambdaQueryWrapper<BizLocation> queryWrapper = new LambdaQueryWrapper<>();
        if (! bizLocationDto.getTitle().isEmpty()) {
            queryWrapper.like(BizLocation::getTitle,  bizLocationDto.getTitle());
        }
        if ( bizLocationDto.getId() != null && !bizLocationDto.getId().isEmpty()) {
            queryWrapper.like(BizLocation::getId, bizLocationDto.getId());
        }
        if ( bizLocationDto.getAddress() != null && !bizLocationDto.getAddress().isEmpty()) {
            queryWrapper.like(BizLocation::getAddress, bizLocationDto.getAddress());
        }
        queryWrapper.orderByDesc(BizLocation::getCreateTime); // 保持按创建时间降序排列

        int pageNum = basePageQuery.getPageNum();
        int pageSize = basePageQuery.getPageSize();
        Page<BizLocation> page = new Page<>(pageNum, pageSize);
        bizLocationService.page(page, queryWrapper); // 执行分页查询
        PageVo pageVo = new PageVo();
        pageVo.setList(page.getRecords()); // 设置查询结果列表
        pageVo.setTotal(page.getTotal());
        return Result.success(pageVo);
    }

    @Operation(summary = "获取网点")
    @GetMapping("/getLocation")
    public Result getLocation() {
        return Result.success(bizLocationService.list());
    }

    @Operation(summary = "微信端获取所有网点信息")
    @GetMapping("/all")
    public Result<List<BizLocation>> getAllLocations() {
        List<BizLocation> locations = bizLocationService.list();
        return Result.success(locations);
    }
}
